package wangjg.android.media.voice;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.util.Log;

public class MyRecordThread extends Thread {
	private int minBufferSize;
	private static int SAMPLE_RATE_IN_HZ = 8000;
	private OutputDisplay display;
	
	private int state;

	public MyRecordThread() {
		minBufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE_IN_HZ, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
	}

	public void run() {
		this.startRecord();
	}
	
	void startRecord(){
		if(state==1 || state==2){
			state=1;
			return;
		}
		state = 1;
		AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE_IN_HZ, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, minBufferSize);
		audioRecord.startRecording();
		short[] buffer = new short[minBufferSize*2];
		int n=0;
		while (state==1 || state==2) {
			int len = audioRecord.read(buffer, 0, minBufferSize);
			if(state==1 && display!=null && (((n++) % 5) ==0)){
				this.printBuffer(buffer, len);
				display.draw(buffer,0,len);
			}else{
//				try {
//					Thread.sleep(200);
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				}
			}
		}
		audioRecord.stop();
		audioRecord.release();
	}
	
	void pause(){
		state=2;
	}
	
	public void stopRecord(){
		state=3;
	}
	
	public void shift(){
		if(state==1){
			state=2;
		}else if(state==2){
			state=1;
		}
	}
	
	public void setDisplay(OutputDisplay display) {
		this.display = display;
	}

	private float getVolume(short[] buffer ,int len){
		int sum = 0;
		for (int i = 0; i < len; i++) {
			// 将 buffer 内容取出，进行平方和运算
			// 这里没有做运算的优化，为了更加清晰的展示代码
			sum += buffer[i] * buffer[i];
		}
		// 平方和除以数据总长度，得到音量大小。可以获取白噪声值，然后对实际采样进行标准化。
		float volume = sum / (float) len;
		return volume;
	}

	private void printBuffer(short[] buffer ,int len){
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < len; i++) {
			int v = ((int)buffer[i]);
			sb.append(v);
			sb.append(',');
		}
		Log.i("len:"+len+",data:", sb.toString());
	}
	
}